<template>
  <view class="feedback-container">
    <view class="feedback-title">意见反馈</view>
    
    <form @submit="submitFeedback">
      <view class="form-item">
        <textarea 
          class="feedback-content" 
          placeholder="请描述您的问题或建议（必填）" 
          v-model="form.content"
          maxlength="500"
          required
        ></textarea>
        <view class="word-count">{{ form.content.length }}/500</view>
      </view>
      
      <view class="form-item">
        <input 
          class="feedback-contact" 
          placeholder="联系方式（邮箱/电话，选填）" 
          v-model="form.contact"
        />
      </view>
      
      <view class="form-item">
        <view class="upload-title">上传图片（最多3张）</view>
        <view class="image-uploader">
          <view 
            class="upload-btn" 
            v-for="(img, index) in images" 
            :key="index"
          >
            <image 
              :src="img.preview" 
              mode="aspectFill" 
              class="preview-image"
              @click="previewImage(index)"
            ></image>
            <view class="delete-btn" @click="removeImage(index)">×</view>
          </view>
          
          <view 
            class="upload-btn add-btn" 
            @click="chooseImage" 
            v-if="images.length < 3"
          >
            <uni-icons type="plusempty" size="30" color="#999"></uni-icons>
          </view>
        </view>
      </view>
      
      <button 
        class="submit-btn" 
        form-type="submit" 
        :disabled="!form.content || submitting"
      >
        {{ submitting ? '提交中...' : '提交反馈' }}
      </button>
    </form>
    
    <uni-popup ref="popup" type="message">
      <uni-popup-message :type="popup.type" :message="popup.message"></uni-popup-message>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        content: '',
        contact: ''
      },
      user: {
        id: null,
        tel: '',
        email: ''
      },
      images: [],
      submitting: false,
      popup: {
        type: 'success',
        message: ''
      }
    }
  },
  onLoad() {
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('user') || {};
        this.user = {
          id: userInfo.id || null,
          tel: userInfo.tel || '',
          email: userInfo.email || ''
        };
        
        // 自动填充联系方式
        if (this.user.tel) {
          this.form.contact = this.user.tel;
        } else if (this.user.email) {
          this.form.contact = this.user.email;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 3 - this.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });

        const newImages = [];
        for (const path of res.tempFilePaths) {
          try {
            const base64 = await this.fileToBase64(path);
            newImages.push({
              preview: path,
              base64: `data:image/${this.getFileType(path)};base64,${base64}`
            });
          } catch (convertError) {
            console.error('图片转换失败:', convertError);
            // 保留原始路径作为预览，但不上传
            newImages.push({
              preview: path,
              base64: null
            });
          }
        }
        
        this.images = [...this.images, ...newImages].slice(0, 3);
      } catch (error) {
        this.handleImageError(error);
      }
    },
    
    async fileToBase64(path) {
      try {
        // 标准化路径
        path = this.normalizeFilePath(path);
        
        // 方法1：直接使用uni.getFileSystemManager
        try {
          const fs = uni.getFileSystemManager();
          const { data } = await new Promise((resolve, reject) => {
            fs.readFile({
              filePath: path,
              encoding: 'base64',
              success: resolve,
              fail: reject
            });
          });
          return data;
        } catch (directError) {
          console.warn('直接读取失败:', directError);
        }

        // 方法2：通过临时文件方式
        try {
          const { tempFilePath } = await new Promise((resolve, reject) => {
            uni.downloadFile({
              url: path,
              success: resolve,
              fail: reject
            });
          });
          
          const fs = uni.getFileSystemManager();
          const { data } = await new Promise((resolve, reject) => {
            fs.readFile({
              filePath: tempFilePath,
              encoding: 'base64',
              success: resolve,
              fail: reject
            });
          });
          return data;
        } catch (downloadError) {
          console.warn('下载方案失败:', downloadError);
        }

        // 方法3：使用plus.io（仅App环境）
        // #ifdef APP-PLUS
        try {
          const fileContent = await new Promise((resolve, reject) => {
            plus.io.resolveLocalFileSystemURL(path, (entry) => {
              entry.file((file) => {
                const fileReader = new plus.io.FileReader();
                fileReader.onloadend = (evt) => {
                  const content = evt.target.result.split(',')[1];
                  resolve(content);
                };
                fileReader.readAsDataURL(file);
              }, reject);
            }, reject);
          });
          return fileContent;
        } catch (plusError) {
          console.warn('plus.io方案失败:', plusError);
        }
        // #endif

        throw new Error('所有转换方案均失败');
      } catch (err) {
        console.error('文件转换失败:', {
          path,
          error: err.message || err
        });
        throw new Error('图片处理失败，请尝试其他图片');
      }
    },
    
    normalizeFilePath(path) {
      // 处理Android路径
      if (path.startsWith('/storage/') && !path.startsWith('file://')) {
        return `file://${path}`;
      }
      // 处理iOS路径
      if (path.startsWith('/var/') && !path.startsWith('file://')) {
        return `file://${path}`;
      }
      // 其他情况原样返回
      return path;
    },
    
    getFileType(path) {
      const extension = path.split('.').pop().toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif'].includes(extension) ? extension : 'jpeg';
    },
    
    async submitFeedback() {
      if (!this.form.content) {
        this.showPopup('error', '请填写反馈内容');
        return;
      }
    
      this.submitting = true;
    
      try {
        // 过滤掉转换失败的图片
        const validImages = this.images.filter(img => img.base64 !== null);
        
        const requestResult = await uni.request({
          url: 'http://192.168.1.42:8000/api/feedback.php',
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: {
            ...this.form,
            user_id: this.user.id,
            images: validImages.map(img => img.base64)
          },
          timeout: 10000
        });
        
        // 兼容不同uni-app版本的返回值
        let response;
        if (Array.isArray(requestResult)) {
          if (requestResult[0]) throw requestResult[0];
          response = requestResult[1];
        } else {
          response = requestResult;
        }
    
        if (!response) {
          throw new Error('请求无响应');
        }
    
        if (response.statusCode !== 200) {
          throw new Error(`服务器返回错误状态: ${response.statusCode}`);
        }
    
        if (!response.data || response.data.status !== 'success') {
          throw new Error(response.data?.message || '提交处理失败');
        }
    
        this.showPopup('success', response.data.message || '提交成功');
        this.resetForm();
        
      } catch (error) {
        let errorMessage = error.message;
        if (error.message.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查网络设置';
        } else if (error.message.includes('timeout')) {
          errorMessage = '请求超时，请稍后再试';
        }
        this.showPopup('error', errorMessage);
        console.error('提交错误详情:', error);
      } finally {
        this.submitting = false;
      }
    },
    
    removeImage(index) {
      this.images.splice(index, 1);
    },
    
    previewImage(index) {
      uni.previewImage({
        current: this.images[index].preview,
        urls: this.images.map(img => img.preview)
      });
    },
    
    handleImageError(error) {
      let message = '图片处理失败';
      if (error.message.includes('permission')) {
        message = '无存储权限，请在设置中开启';
      } else if (error.message.includes('cancel')) {
        return; // 用户取消不提示
      }
      
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      });
    },
    
    showPopup(type, message) {
      this.popup.type = type;
      this.popup.message = message;
      this.$refs.popup.open();
    },
    
    resetForm() {
      this.form = { content: '', contact: '' };
      this.images = [];
    }
  }
}
</script>

<style scoped>
.feedback-container {
  padding: 20px;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.feedback-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.form-item {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.feedback-content {
  width: 100%;
  height: 150px;
  font-size: 14px;
  line-height: 1.5;
  border: none;
  background-color: transparent;
}

.word-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.feedback-contact {
  width: 100%;
  height: 40px;
  font-size: 14px;
  border: none;
  background-color: transparent;
}

.upload-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
}

.upload-btn {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #ddd;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  right: 0;
  top: 0;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0 0 0 10px;
  font-size: 12px;
}

.submit-btn {
  background-color: #007aff;
  color: white;
  border-radius: 8px;
  margin-top: 20px;
  height: 45px;
  line-height: 45px;
  font-size: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}


.submit-btn[disabled] {
  background-color: #ccc;
}
</style>